package org.prs.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.validator.GenericValidator;
import org.prs.model.User;
import org.prs.persistence.UserDatabasePersitenceManager;
import org.prs.service.PasswordService;

public class NewUserServlet extends HttpServlet {

    private User newUser = new User();
    private UserDatabasePersitenceManager persistUser = new UserDatabasePersitenceManager();

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            HttpSession session = request.getSession(true);
            newUser.setUsername(request.getParameter("username"));
            newUser.setPassword(request.getParameter("password"));
            newUser.setLastName(request.getParameter("lastname"));
            newUser.setFirstName(request.getParameter("firstname"));
            newUser.setMiddleName(request.getParameter("middlename"));
            try {
                newUser.setUserLevel(Integer.parseInt(request.getParameter("userlevel")));
            } catch (NumberFormatException e) {
            }
            boolean valid = true;
            StringBuilder userCreationMessage = new StringBuilder();

            if (GenericValidator.isBlankOrNull(newUser.getUsername())) {
                valid = false;
                userCreationMessage.append("<div id='inputerror'>Username is null</div>");
            } else if (newUser.getUsername().length() < 6) {
                valid = false;
                userCreationMessage.append("<div id='inputerror'>Username length is less than 6 characters</div>");
            }
            if (GenericValidator.isBlankOrNull(newUser.getLastName())) {
                valid = false;
                userCreationMessage.append("<div id='inputerror'>Last Name is null</div>");
            }
            if (GenericValidator.isBlankOrNull(newUser.getPassword())) {
                valid = false;
                userCreationMessage.append("<div id='inputerror'>Password is null</div>");
            } else if (newUser.getPassword().length() < 6) {
                valid = false;
                userCreationMessage.append("<div id='inputerror'>Username length is less than 6 characters</div>");
            } else if (!newUser.getPassword().equals(request.getParameter("confirmpassword"))) {
                valid = false;
                userCreationMessage.append("<div id='inputerror'>Password and confirm passwords are not similar</div>");
            }
            if (GenericValidator.isBlankOrNull(newUser.getFirstName())) {
                valid = false;
                userCreationMessage.append("<div id='inputerror'>First Name is null</div>");
            }
            
            if (!valid) {
                session.setAttribute("usercreationmsg", userCreationMessage.toString());
                response.sendRedirect("newUser.jsp");
            } else {
                newUser.setPassword(PasswordService.getInstance().encrypt(request.getParameter("password")));
                boolean exists = persistUser.checkIfUserExists(newUser);
                if (exists) {

                    userCreationMessage.append("<div id='successmsg'>An user exists with the same Username</div>");
                    session.setAttribute("usercreationmsg", userCreationMessage.toString());
                    response.sendRedirect("newUser.jsp");
                } else {
                    boolean inserted = persistUser.insertUser(newUser);
                    if (inserted) {
                        userCreationMessage.append("<div id='inputerror'>The user was created successfully</div>");
                        session.setAttribute("usercreationmsg", userCreationMessage.toString());
                        response.sendRedirect("newUser.jsp");
                    }
                }
            }

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
